<?php

namespace plugin\admin\app\controller;

use DateTime;
use Exception;
use support\Request;
use support\Response;
use plugin\admin\app\model\TaskLog;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 上品记录 
 */
class TaskLogController extends Crud
{
    
    /**
     * @var TaskLog
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new TaskLog;
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     * @throws Exception
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        // 判断如果是管理员还是操作员
        $admin = admin();
        if($admin['roles'][0] != 1) {
            $where['company_id'] = $admin['company_id'];
        }
        $query = $this->doSelect($where, $field, $order);
        if ($format === 'select') {
            return $this->formatSelect($query->get());
        }
        $paginator = $query->paginate($limit);
        $items = $paginator->items();
        foreach ($items as $key => $value) {
            $data = json_decode($value['data'], true);
            $items[$key]['goods_title'] = $data['goodsInfo']['item']['title'] ?? '';
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $paginator->total(), 'data' => $items]);
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('task-log/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('task-log/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('task-log/update');
    }

    public function deleteNoConsume(Request $request): Response
    {
        // 删除三天前的未消费成功的数据
        // 使用DateTime类来计算三天前的日期
        $date = new DateTime();
        $date->modify('-3 days');
        $threeDaysAgo = $date->format('Y-m-d');
        $num = TaskLog::where('consume_status', 0)
            ->where('created_at', '<', $threeDaysAgo)->delete();
        return $this->json(0, 'ok', ['num' => $num]);
    }

}
